package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.springbootinit.mapper.ProductParamMapper;
import com.graduation.springbootinit.model.entity.ShopPart.ProductParam;
import com.graduation.springbootinit.service.ProductParamService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductParamServiceImpl extends ServiceImpl<ProductParamMapper, ProductParam>
        implements ProductParamService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateParams(Long productId, Map<String, String> params) {
        // 获取现有参数
        QueryWrapper<ProductParam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        List<ProductParam> existingParams = list(queryWrapper);
        Map<String, ProductParam> existingParamMap = new HashMap<>();
        existingParams.forEach(param -> existingParamMap.put(param.getParamKey(), param));
        
        // 遍历新参数
        params.forEach((key, value) -> {
            ProductParam existingParam = existingParamMap.get(key);
            if (existingParam == null) {
                // 不存在则新增
                ProductParam newParam = new ProductParam();
                newParam.setProductId(productId);
                newParam.setParamKey(key);
                newParam.setParamValue(value);
                save(newParam);
            } else if (!existingParam.getParamValue().equals(value)) {
                // 存在且值不同则更新
                existingParam.setParamValue(value);
                updateById(existingParam);
            }
            // 值相同则不处理
        });
    }

    @Override
    public void deleteByProductId(Long productId) {
        QueryWrapper<ProductParam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        remove(queryWrapper);
    }

    @Override
    public Map<String, String> getParamsByProductId(Long productId) {
        QueryWrapper<ProductParam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        List<ProductParam> params = list(queryWrapper);
        
        Map<String, String> result = new HashMap<>();
        params.forEach(param -> result.put(param.getParamKey(), param.getParamValue()));
        return result;
    }
} 